import queue
import threading
import time


class MessageLoop:
    def __init__(self):
        self.queue = queue.Queue()
        self.timeout = 0
        self.running = False

    def loop(self, timeout):
        self.timeout = timeout
        self.running = True
        while self.running:
            try:
                task = self.queue.get(True)
                if task:
                    print("[%d] Execute task in thread" % threading.get_ident())
                    task()
            except queue.Empty:
                break
        self.queue.empty()
        print("[%d] Message loop finished" % threading.get_ident())

    def post(self, task):
        if not callable(task):
            raise Exception("%s is not callable" % str(task))
        self.queue.put_nowait(task)

    def running(self):
        return self.running

    def quit(self):
        self.queue.empty()

        def quitTask():
            self.running = False
        self.post(quitTask)


def closureTest(task):
    print(task())


if __name__ == "__main__":
    print("[%d] Hello MessageLoop" % (threading.get_ident()))
    x = 1
    y = 2

    messageLoop = MessageLoop()

    def run():
        messageLoop.loop(0)
    thread = threading.Thread(target=run)
    thread.start()

    def task():
        print("[%d] task result %d" % (threading.get_ident(), x + y))
    messageLoop.post(task)
    messageLoop.quit()
    thread.join()
    print("[%d] Main thread quit" % (threading.get_ident()))


